package com.example.library.config;

import com.example.library.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * JWT认证过滤器
 *
   */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        
        // 获取请求路径
        String requestPath = request.getRequestURI();
        
        // 跳过不需要认证的路径
        if (isPublicPath(requestPath)) {
            filterChain.doFilter(request, response);
            return;
        }
        
        try {
            // 从请求头中获取token
            String token = jwtUtils.getTokenFromRequest(request);
            
            if (StringUtils.isNotBlank(token) && jwtUtils.isValidToken(token)) {
                // 从token中获取用户信息
                Long userId = jwtUtils.getUserIdFromToken(token);
                String username = jwtUtils.getUsernameFromToken(token);
                String role = jwtUtils.getRoleFromToken(token);
                
                // 创建认证对象
                UsernamePasswordAuthenticationToken authentication = 
                    new UsernamePasswordAuthenticationToken(
                        userId,
                        null,
                        Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role.toUpperCase()))
                    );
                
                // 设置到安全上下文
                SecurityContextHolder.getContext().setAuthentication(authentication);
                
                log.debug("用户{}认证成功，角色：{}", username, role);
            } else {
                log.debug("Token无效或已过期");
            }
        } catch (Exception e) {
            log.error("JWT认证失败：{}", e.getMessage());
        }
        
        filterChain.doFilter(request, response);
    }
    
    /**
     * 判断是否为公开路径（不需要认证）
     */
    private boolean isPublicPath(String path) {
        String[] publicPaths = {
            "/api/users/login",
            "/api/users/register",
            "/api/users/check/username",
            "/api/users/check/email",
            "/api/users/check/phone",
            "/api/books/popular",
            "/api/books/latest",
            "/api/books/recommended",
            "/api/categories/tree",
            "/api/categories/enabled",
            "/actuator/**",
            "/swagger-ui/**",
            "/v3/api-docs/**"
        };
        
        for (String publicPath : publicPaths) {
            if (path.startsWith(publicPath.replace("/**", ""))) {
                return true;
            }
        }
        
        return false;
    }

}